# -*- coding: utf-8 -*-
from flask import current_app
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
import datetime
from .. import db


class User(UserMixin, db.Model):
	"""用户表"""
	__tablename__ = 'users'
	id = db.Column(db.Integer, primary_key=True)
	mobile = db.Column(db.String(32), index=True, unique=True, nullable=False)
	username = db.Column(db.String(50), index=True, nullable=False)
	nickname = db.Column(db.String(50))
	city = db.Column(db.String(255))
	industry = db.Column(db.String(255))
	gender = db.Column(db.String(8), default="m", comment="m, f")
	email = db.Column(db.String(128))
	password = db.Column(db.String(128), nullable=False)
	salts = db.Column(db.String(128))
	role_type = db.Column(db.String(128), default="normal", comment="admin, expert, normal")
	avatar = db.Column(db.Text)
	openid = db.Column(db.String(255))
	unionid = db.Column(db.String(255))
	workflow_state = db.Column(db.String(255), nullable=False, default="active", comment="active, inactive")
	last_login_at = db.Column(db.DateTime)
	login_ip = db.Column(db.String(64), default="")
	created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now())
	updated_at = db.Column(db.DateTime, default=datetime.datetime.now())

	def __repr__(self):
		return '<username %r>' % self.username

	# def __init__(self, mobile, password, username, email):
	# 	self.mobile = mobile
	# 	self.passwd = password
	# 	self.username = username
	# 	self.email = email

	@staticmethod
	def insert_admin_user(data):
		user = User.query.filter_by(mobile=data["mobile"]).first()
		if user:
			return {"errcode": 400, "errmsg": "user is exit",
					"data": {"id": user.id, "mobile": user.mobile, "username": user.username, "nickname": user.nickname}}
		user = User(**data)
		db.session.add(user)
		try:
			db.session.commit()
			return {"errcode": 200, "errmsg": "ok",
					"data": {"id": user.id, "mobile": user.mobile, "username": user.username, "nickname": user.nickname}}
		except Exception as e:
			return {"errcode": 400, "errmsg": str(e)}

	@property
	def passwd(self):
		raise AttributeError('password is not a readable attribute')

	@passwd.setter
	def passwd(self, passwd):
		self.password = generate_password_hash(str(passwd))

	def verify_password(self, passwd):
		return check_password_hash(self.password, str(passwd))

	# token 验证
	def generate_auth_token(self, expiration=7200):
		s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)
		return s.dumps({'id': self.id}).decode('ascii')

	@staticmethod
	def verify_auth_token(token):
		s = Serializer(current_app.config['SECRET_KEY'])
		try:
			data = s.loads(token)
		except Exception as e:
			return None
		return User.query.get(data['id'])

	def verify_password_or_token(self, token, passwd):
		user = User.verify_auth_token(token)
		if user:
			return True
		return check_password_hash(self.password, str(passwd))

	def generate_auth_jwt_token(self, expiration=7200):
		s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)
		return s.dumps({'id': self.id}).decode('ascii')

	def get_user_by_mobile(self, mobile):
		return User.query.filter_by(self.mobile == mobile).first()

	@staticmethod
	def is_exist(data):
		"""
		:param data: {"key": ""value}
		:return: Object or False
		"""
		user = User.query.filter_by(**data).first()
		return user if user else False
